<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>在线OJ-题⽬列表</title>
    <style>
        /* 基础样式保持不变 */
        * {
            margin: 0px;
            padding: 0px;
        }

        html,
        body {
            width: 100%;
            height: 100%;
        }

        .container .navbar {
            width: 100%;
            height: 50px;
            background-color: black;
            overflow: hidden;
        }

        .container .navbar a {
            display: inline-block;
            width: 80px;
            color: white;
            font-size: large;
            line-height: 50px;
            text-decoration: none;
            text-align: center;
        }

        .container .navbar a:hover {
            background-color: green;
        }

        .container .navbar .user-area {
            float: right;
            display: flex;
            align-items: center;
        }

        .container .navbar .username {
            color: white;
            line-height: 50px;
            margin-right: 10px;
            margin-left: 10px;
        }

        .container .question_list {
            padding-top: 50px;
            width: 800px;
            height: 100%;
            margin: 0px auto;
            text-align: center;
        }

        .container .question_list table {
            width: 100%;
            font-size: large;
            font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
            margin-top: 50px;
            background-color: rgb(243, 248, 246);
        }

        .container .question_list h1 {
            color: green;
        }

        .container .question_list table .item {
            width: 100px;
            height: 40px;
            font-size: large;
            font-family: 'Times New Roman', Times, serif;
        }

        .container .question_list table .item a {
            text-decoration: none;
            color: black;
        }

        .container .question_list table .item a:hover {
            color: blue;
            text-decoration: underline;
        }

        .container .footer {
            width: 100%;
            height: 50px;
            text-align: center;
            line-height: 50px;
            color: #ccc;
            margin-top: 15px;
        }

        /* 提示框样式 */
        .alert {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            padding: 10px 20px;
            background-color: #f44336;
            color: white;
            border-radius: 4px;
            display: none;
            z-index: 1000;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 导航栏 -->
        <div class="navbar">
            <a href="/">⾸⻚</a>
            <a href="/all_questions">题库</a>
            <a href="#">竞赛</a>
            <a href="#">讨论</a>
            <a href="#">求职</a>
            
            <!-- 用户区域：先显示昵称，再显示退出 -->
            <div class="user-area">
                <span class="username" id="usernameDisplay" style="display: none;"></span>
                <a class="login" id="logoutBtn" href="#" style="display: none;">退出</a>
                <a class="login" id="loginBtn" href="#">登录</a>
            </div>
        </div>

        <!-- 提示框 -->
        <div class="alert" id="loginAlert">请先登录再答题！</div>

        <div class="question_list">
            <h1>OnlineJuge题⽬列表</h1>
            <table>
                <tr>
                    <th class="item">编号</th>
                    <th class="item">标题</th>
                    <th class="item">难度</th>
                </tr>
                {{#question_list}}
                <tr>
                    <td class="item">{{number}}</td>
                    <td class="item"><a href="/question/{{number}}" class="question-link">{{title}}</a></td>
                    <td class="item">{{star}}</td>
                </tr>
                {{/question_list}}
            </table>
        </div>
        <div class="footer">
            <h4>@小沈YO.</h4>
        </div>
    </div>

    <script>
        // 页面加载时检查登录状态
        window.onload = function() {
            checkLoginStatus();
            sortQuestionList(); // 新增：渲染后排序
            bindQuestionLinks();
        };

        // 检查登录状态并更新导航栏
        function checkLoginStatus() {
            return fetch('/api/check_login')
                .then(res => res.text())
                .then(username => {
                    const usernameDisplay = document.getElementById('usernameDisplay');
                    const logoutBtn = document.getElementById('logoutBtn');
                    const loginBtn = document.getElementById('loginBtn');

                    if (username !== 'not_login' && username.trim() !== '') {
                        // 登录状态：显示用户名和退出按钮，隐藏登录按钮
                        usernameDisplay.textContent = username;
                        usernameDisplay.style.display = 'inline-block';
                        logoutBtn.style.display = 'inline-block';
                        loginBtn.style.display = 'none';
                    } else {
                        // 未登录状态：显示登录按钮，隐藏用户名和退出按钮
                        usernameDisplay.style.display = 'none';
                        logoutBtn.style.display = 'none';
                        loginBtn.style.display = 'inline-block';
                    }
                    return username; // 返回登录状态供其他函数使用
                })
                .catch(error => {
                    console.error('检查登录状态出错:', error);
                    return 'not_login'; // 出错时默认视为未登录
                });
        }

        // 对题目列表按 number 升序排序（关键修复）
        function sortQuestionList() {
            const table = document.querySelector('.question_list table');
            if (!table) return;

            const rows = Array.from(table.querySelectorAll('tr')).slice(1); // 跳过表头
            rows.sort((a, b) => {
                const numA = parseInt(a.cells[0].textContent);
                const numB = parseInt(b.cells[0].textContent);
                return numA - numB;
            });

            // 清空现有行（除表头）并重新插入排序后的行
            rows.forEach(row => table.appendChild(row));
        }

        // 绑定题目链接点击事件
        function bindQuestionLinks() {
            const questionLinks = document.querySelectorAll('.question-link');
            questionLinks.forEach(link => {
                link.addEventListener('click', function(e) {
                    // 先检查登录状态再决定是否允许跳转
                    checkLoginStatus().then(username => {
                        if (username === 'not_login' || username.trim() === '') {
                            // 未登录：阻止跳转并显示提示
                            e.preventDefault();
                            const alert = document.getElementById('loginAlert');
                            alert.style.display = 'block';
                            // 3秒后隐藏提示
                            setTimeout(() => {
                                alert.style.display = 'none';
                            }, 3000);
                        }
                        // 已登录：允许默认跳转行为
                    });
                });
            });
        }

        // 绑定退出登录事件：退出后直接跳转到主页
        document.getElementById('logoutBtn').addEventListener('click', function(e) {
            e.preventDefault();
            fetch('/api/logout')
                .then(() => {
                    // 退出成功后立即跳转到主页
                    window.location.href = '/';
                })
                .catch(error => {
                    console.error('退出登录错误:', error);
                });
        });
    </script>
</body>

</html>